<template>
	<canvas class="watermark-canvas" id="watermark-canvas" canvas-id="watermark-canvas"
		:style="{ width: canvasWidth, height: canvasHeight }" />
	<!-- <uni-icons type="image" size="30" @click="chooseImage()"></uni-icons>
	<image :src="image" mode="" v-if="image" style="width: 500rpx;height:500rpx"></image> -->
	<!-- 当前位置经纬度 -->
	<Lotlats @position="position"></Lotlats>
</template>

<script setup lang="ts">
	import * as AMapLoader from '@amap/amap-jsapi-loader';
	import { showLoading, successToast, errorToast } from '@/utils/prompt';
	import { ref } from 'vue';
	import { format, subDays, getDay } from 'date-fns';
	import Lotlats from '@c/team/Lotlat.vue';
	import { useUserStore } from '@/stores/user';
	const userInfo = useUserStore();
	const longitude = ref()
	const latitude = ref()
	const locName = ref('')
	const locRoad = ref('')
	const locLine = ref('')
	const props = defineProps({
		//最多可以选择的图片张
		maxChooseCount: {
			type: Number,
			default: 9
		},
		//album 从相册选图，camera 使用相机
		sourceTypes: {
			type: Array,
			default: function () {
				return ['camera', 'album']
			}
		},
		//自定义文字
		title: {
			type: String,
			default: ''
		},
	});
	const canvasWidth = ref()
	const canvasHeight = ref()
	const image = ref()
	const emit = defineEmits(['selected']);
	if (!userInfo.realname) {
		userInfo.getUserInfo()
	}

	function famartWeek() {
		const e = getDay(new Date())
		switch (e) {
			case 0:
				return '星期日'
			case 1:
				return '星期一'
			case 2:
				return '星期二'
			case 3:
				return '星期三'
			case 4:
				return '星期四'
			case 5:
				return '星期五'
			case 6:
				return '星期六'
		}
	}
	/**
	 * 获取当前城市信息
	 * @param  lat 当前位置的纬度
	 * @param  lot 当前位置的经度
	 * @return MapPage 修改地图页面的first状态
	 */
	function position(lat : number, lot : number) {
		console.log(JSON.stringify(lat) + '*****')
		longitude.value = lot;
		latitude.value = lat;
		getPositionByLonLats(lot, lat)
	}
	function getPositionByLonLats(lng : number, lat : number) {
		AMapLoader.load({
			key: '28c93d7518383bfa130b6c7cd239c331', // 申请好的Web端开发者Key，首次调用 load 时必填  
			version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
			plugins: ['AMap.Geocoder', 'AMap.Geolocation'] //插件列表
		})
			.then(AMap => {
				const lnglat = [lng, lat]
				const geocoder = new AMap.Geocoder()
				geocoder.getAddress(lnglat, function (status, result) {
					if (status === 'complete' && result.regeocode) {
						// console.log(JSON.stringify(result.regeocode))
						const lot = result.regeocode.formattedAddress
						locName.value = lot.slice(0, 23)
						locRoad.value = lot.slice(23, 46)
						locLine.value = lot.slice(46, 69)
					} else {
						errorToast('查询地址失败')
					}
				})
			})
			.catch(e => {
				console.log(e + '*******')
			})
	}
	// function chooseImage() {
	// 	uni.chooseImage({
	// 		count: props.maxChooseCount,
	// 		sizeType: ['compressed'],
	// 		sourceType: props.sourceTypes,
	// 		success: async (res) => {
	// 			let filePath = res.tempFilePaths[0]
	// 			fillTextToImg(filePath)
	// 		}
	// 	})
	// }
	function sleep(millisecond) {
		return new Promise((resolve) => {
			setTimeout(resolve, millisecond)
		})
	}
	function fillTextToImg(file) {
		return new Promise((resolve, reject) => {
			showLoading('正在提交')
			uni.getImageInfo({
				src: file,
				success: async res => {
					//设置画布大小，然后再画，不然会只画一部分
					// canvasWidth.value = `${res.width}px`
					// canvasHeight.value = `${res.height}px`
					res.width = 650
					res.height = 800
					canvasWidth.value = `650px`
					canvasHeight.value = `800px`
					console.log(res.width, res.height);
					const bol = res.width < res.height
					let waterW = Number(res.width)
					if (bol && waterW < 650) {
						waterW = 650
					}
					if (bol && waterW > 800) {
						waterW = 800
					}
					if (!bol) {
						waterW = 800
					}
					await sleep(200)
					const ctx = uni.createCanvasContext('watermark-canvas')
					ctx.clearRect(0, 0, res.width, res.height)
					ctx.beginPath()
					ctx.drawImage(res.path, 0, 0, res.width, res.height)
					// 水印 字体大小，颜色，内容，位置
					ctx.beginPath()
					ctx.font = 'bold 24px 黑体'
					const now = new Date();
					let start = format(now, 'yyyy-MM-dd HH:mm:ss');

					console.log(famartWeek() + '------')
					const name = userInfo.realname ? userInfo.realname : userInfo.nickname
					// 背景
					let fw = waterW / 12
					ctx.setFillStyle('#ffffff')
					ctx.setFontSize(waterW / 24)
					ctx.fillText(props.title, 10, res.height / 4 * 2.6)
					ctx.fillText(name, 10, res.height / 4 * 2.8)
					ctx.setFontSize(waterW / 24)
					ctx.fillText('安蓝环保', 10, res.height / 4 * 2.8 + fw * 1.4 * 0.5)
					ctx.setFontSize(waterW / 24)
					ctx.fillText(famartWeek(), 10, res.height / 4 * 2.8 + fw * 1.4 * 1)
					ctx.setFontSize(waterW / 24)
					ctx.fillText(start, 10, res.height / 4 * 2.8 + fw * 1.4 * 1.5)
					ctx.setFontSize(waterW / 24)
					ctx.fillText(locName.value, 10, res.height / 4 * 2.8 + fw * 1.4 * 2)
					ctx.setFontSize(waterW / 24)
					ctx.fillText(locRoad.value, 10, res.height / 4 * 2.8 + fw * 1.4 * 2.5)
					ctx.setFontSize(waterW / 24)
					ctx.fillText(locLine.value, 10, res.height / 4 * 2.8 + fw * 1.4 * 3)
					// 开始绘制 (canvas -> 临时文件路径)
					ctx.draw(false, async () => {
						await sleep(500) // 某些平台 canvas 渲染慢，需要等待
						uni.canvasToTempFilePath({
							canvasId: 'watermark-canvas',
							destWidth: res.width,
							destHeight: res.height,
							fileType: 'jpg',
							quality: 0.8,
							success: (fileRes) => {
								resolve(fileRes.tempFilePath)
								image.value = fileRes.tempFilePath
								emit('selected', fileRes.tempFilePath);
								uni.hideLoading();
							},
							fail: (err) => {
								uni.showToast({
									title: err.errMsg,
									icon: 'none'
								})
								reject()
							},
						})
					})
				},
				fail: (err) => {
					console.log('[Error getImageInfo]', err)
					uni.showToast({
						title: err.errMsg,
						icon: 'none'
					})
					reject()
				},
			})
		});
	}
	defineExpose({
		fillTextToImg,
	});
</script>

<style scoped lang="less">
	.watermark-canvas {
		transform: scale(1);
		transform-origin: 0 0;
		position: absolute;
		top: -999px;
		left: -999px;
	}
</style>